import {
	getSearchHistory,
	getSearchPopular,
} from '../../../services/good/fetchSearchHistory';

Page({
	data: {
		historyWords: [],//历史搜索列表
		searchValue: '',//输入框值
		goodsList: [],//查询商品
		popularWords: [],
		dialog: {
			title: '确认删除当前历史记录',
			showCancelButton: true,
			message: '',
		},
		dialogShow: false,
	},

	deleteType: 0,
	deleteIndex: '',
	//定时器id
	timerId: -1,

	onShow() {
		this.queryHistory();
		this.queryPopular();
	},
	//历史记录
	async queryHistory() {
		try {
			const list = await getSearchHistory();
			const code = 'Success';
			if (String(code).toUpperCase() === 'SUCCESS') {
				const historyWords = list.data;
				this.setData({
					historyWords,
				});
			}
		} catch (error) {
			console.error(error);
		}
	},
	//输入框搜索事件
	handleSubmit(e) {
		//只要出发input事件 那么就直接清除上一个定时器即可
		clearTimeout(this.timerId);
		let { value } = e.detail;
		value = value.trim();//去除空格
		if (!value) {
			this.setData({
				goodsList: []
			})
			return;
		}
		//通过获取到的value值 向后端发起查询商品请求
		clearTimeout(this.timerId)
		this.timerId = setTimeout(() => {
			this.getGoodsSearch(value)
		}, 1000)

	},
	//商品查询
	getGoodsSearch(queryValue) {
		//历史记录相关功能
		let { historyWords } = this.data;
		let index = historyWords.findIndex(item => item === queryValue);
		if (index === -1) historyWords.push(queryValue)
		if (queryValue) {
			wx.navigateTo({
				url: `/pages/goods/result/index?searchValue=${queryValue}`,
			});
		}
	},

	//历史搜索点击事件
	handleHistoryTap(e) {
		const { historyWords } = this.data;
		const { dataset } = e.currentTarget;
		const _searchValue = historyWords[dataset.index || 0] || '';
		if (_searchValue) {
			wx.navigateTo({
				url: `/pages/goods/result/index?searchValue=${_searchValue}`,
			});
		}
	},

	async queryPopular() {
		try {
			const data = await getSearchPopular();
			const code = 'Success';
			if (String(code).toUpperCase() === 'SUCCESS') {
				const { popularWords = [] } = data;
				this.setData({
					popularWords,
				});
			}
		} catch (error) {
			console.error(error);
		}
	},

	confirm() {
		const { historyWords } = this.data;
		const { deleteType, deleteIndex } = this;
		historyWords.splice(deleteIndex, 1);
		if (deleteType === 0) {
			this.setData({
				historyWords,
				dialogShow: false,
			});
		} else {
			this.setData({ historyWords: [], dialogShow: false });
		}
	},

	close() {
		this.setData({ dialogShow: false });
	},

	handleClearHistory() {
		const { dialog } = this.data;
		this.deleteType = 1;
		this.setData({
			dialog: {
				...dialog,
				message: '确认删除所有历史记录',
			},
			dialogShow: true,
		});
	},

	deleteCurr(e) {
		const { index } = e.currentTarget.dataset;
		const { dialog } = this.data;
		this.deleteIndex = index;
		this.setData({
			dialog: {
				...dialog,
				message: '确认删除当前历史记录',
				deleteType: 0,
			},
			dialogShow: true,
		});
	},


});
